package com.traffic.between.annotation;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.log.Logger;
import com.jfinal.plugin.IPlugin;
import com.traffic.between.adaptor.IAdaptor;

public class InterfaceProviderPlugin implements IPlugin {

	protected final Logger log = Logger.getLogger(InterfaceProviderPlugin.class);

	private final static ConcurrentHashMap<String, Object> interfaceProviders = new ConcurrentHashMap<String, Object>();

	public boolean start() {
		List<Class<? extends IAdaptor>> modelClasses = ClassSearcherUtils.of(IAdaptor.class).search();
		for (Class<? extends IAdaptor> c : modelClasses) {
			// 获取注解对象
			ChooseProvider provider = (ChooseProvider) c.getAnnotation(ChooseProvider.class);
			if (provider == null) {
				log.error(c.getName() + "继承了IConverter，但是没有注解绑定接口 ！！！");
				break;
			}
			String channelName = provider.channel().trim();
			if (channelName == null || "".equals(channelName)) {
				log.error(c.getName() + "继承了IConverter，但是没有绑定具体的渠道 ！！！");
				break;
			}
			try {
				interfaceProviders.put(channelName, c.newInstance());
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}

		return true;
	}

	public static Object getAdaptorByChannel(String channel) {

		return interfaceProviders.get(channel);
	}

	public boolean stop() {

		return false;
	}

}
